import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import type { PlatformUser, PlatformLoginRequest, PlatformLoginResponse } from '../types/platform';
import { platformApiService } from '../services/platform/api/platformApi';

// 平台状态接口
interface PlatformState {
  // 用户状态
  user: PlatformUser | null;
  token: string | null;
  permissions: string[];
  menuCodes: string[];  // 添加菜单编码状态
  accessibleTenants: string[];
  isAuthenticated: boolean;
  isLoading: boolean;
  
  // 平台数据状态
  currentTenant: string | null;  // 当前查看的租户ID
  
  // Actions
  login: (credentials: PlatformLoginRequest) => Promise<void>;
  logout: () => Promise<void>;
  setCurrentTenant: (tenantId: string | null) => void;
  canAccessTenant: (tenantId: string) => boolean;
  refreshUserInfo: () => Promise<void>;
}

// 创建平台状态管理
export const usePlatformStore = create<PlatformState>()(
  devtools(
    persist(
      (set, get) => ({
        // 初始状态
        user: null,
        token: null,
        permissions: [],
        menuCodes: [],
        accessibleTenants: [],
        isAuthenticated: false,
        isLoading: false,
        currentTenant: null,

        // 登录
        login: async (credentials: PlatformLoginRequest) => {
          set({ isLoading: true });
          try {
            const response: PlatformLoginResponse = await platformApiService.login(credentials);
            // 先检查数据结构
            if (!response) {
              throw new Error('登录响应为空');
            }
            
            // 存储token到localStorage（需要在调用getCurrentUser之前设置）
            localStorage.setItem('platform_token', response.accessToken);
            
            // 登录成功后调用getCurrentUser获取完整用户信息包括菜单代码
            const currentUserInfo = await platformApiService.getCurrentUser();
            
            set({
              user: {
                ...response.user,
                menuCodes: currentUserInfo.menuCodes || [],
              },
              token: response.accessToken,
              permissions: response.permissions,
              menuCodes: currentUserInfo.menuCodes || [],
              accessibleTenants: response.accessibleTenants || [],
              isAuthenticated: true,
              isLoading: false,
            });
            
            console.log('平台登录成功:', response.user);
            console.log('获取到的菜单代码:', currentUserInfo.menuCodes);
            
            // 导航到默认的平台仪表盘
            window.location.href = '/platform/dashboard';
          } catch (error) {
            console.error('登录失败，错误详情:', error);
            set({ isLoading: false });
            throw error;
          }
        },

        // 登出
        logout: async () => {
          const { token } = get();
          
          set({ isLoading: true });
          
          try {
            // 如果有token，尝试调用后端登出API
            if (token) {
              await platformApiService.logout();
            }
          } catch (error) {
            // 即使后端登出失败，也要清除本地状态
            console.warn('后端登出API调用失败，但仍将清除本地状态:', error);
          } finally {
            // 无论API调用成功与否，都清除本地状态
            set({
              user: null,
              token: null,
              permissions: [],
              menuCodes: [],
              accessibleTenants: [],
              isAuthenticated: false,
              currentTenant: null,
              isLoading: false,
            });
            
            // 清除localStorage
            localStorage.removeItem('platform_token');
            localStorage.removeItem('platform_user');
            
            console.log('平台登出成功');
          }
        },

        // 设置当前租户
        setCurrentTenant: (tenantId: string | null) => {
          const state = get();
          
          // 检查是否有权限访问该租户
          if (tenantId && !state.canAccessTenant(tenantId)) {
            console.warn('无权限访问租户:', tenantId);
            return;
          }
          
          set({ currentTenant: tenantId });
        },

        // 检查是否可以访问指定租户
        canAccessTenant: (tenantId: string) => {
          const { user, accessibleTenants } = get();
          
          // 超级管理员可以访问所有租户
          if (user?.isSuperAdmin) {
            return true;
          }
          
          // 空数组表示可以访问所有租户
          if (accessibleTenants.length === 0) {
            return true;
          }
          
          // 检查是否在允许访问的租户列表中
          return accessibleTenants.includes(tenantId);
        },

        // 刷新用户信息
        refreshUserInfo: async () => {
          const { token } = get();
          if (!token) {
            return;
          }

          set({ isLoading: true });
          try {
            // 调用获取用户信息的API
            const userInfo = await platformApiService.getCurrentUser();
            set({ 
              user: userInfo,
              permissions: userInfo.permissions || [],
              menuCodes: userInfo.menuCodes || []
            });
            
            console.log('用户信息刷新成功，菜单信息:', userInfo.menuCodes);
          } catch (error) {
            console.error('刷新用户信息失败:', error);
            // 如果token无效，则登出
            get().logout();
          } finally {
            set({ isLoading: false });
          }
        },
      }),
      {
        name: 'platform-store',
        // 只持久化部分状态
        partialize: (state) => ({
          user: state.user,
          token: state.token,
          permissions: state.permissions,
          menuCodes: state.menuCodes,
          accessibleTenants: state.accessibleTenants,
          isAuthenticated: state.isAuthenticated,
          currentTenant: state.currentTenant,
        }),
      }
    ),
    {
      name: 'platform-store',
    }
  )
);

// 租户访问权限Hook
export const usePlatformTenantAccess = () => {
  const { canAccessTenant, accessibleTenants, user, setCurrentTenant, currentTenant } = usePlatformStore();
  
  return {
    canAccessTenant,
    accessibleTenants,
    isSuperAdmin: user?.isSuperAdmin || false,
    setCurrentTenant,
    currentTenant,
    canAccessAllTenants: user?.isSuperAdmin || accessibleTenants.length === 0,
  };
};

// 初始化平台状态（应用启动时调用）
export const initializePlatformStore = () => {
  const token = localStorage.getItem('platform_token');
  
  if (token) {
    // 这里可以验证token的有效性
    console.log('发现已保存的平台token，尝试自动登录...');
    
    // 如果token有效，可以恢复用户状态
    // 这里暂时简化处理，实际应用中应该验证token
    const state = usePlatformStore.getState();
    if (state.user && state.isAuthenticated) {
      console.log('平台自动登录成功');
    }
  }
};

export default usePlatformStore;